<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>JS的事件监听机制 - db's jim - 博客园</title>
        <link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/aji88/rss"/>
        <link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/aji88/rsd.xml"/>
        <link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/aji88/wlwmanifest.xml"/>
        <script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script>
        <script type="text/javascript">var currentBlogApp = 'aji88', cb_enable_mathjax=false;</script>
        <script src="https://raw.githubusercontent.com/placemarker/jQuery-MD5/master/jquery.md5.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function(){
              $(document).click(function(event){
                                console.log("click");
                                });
              $(window).scroll(function(event){
                               //console.log("scroll");
                               });
              $(document).keyup(function(event){
                                console.log("keyevent: "+ event.which);
                                });
              $("*").each(function(){
                          if(!$(this).attr("id")) {
                          $(this).attr("id",$.md5(this.outerHTML));
                          }
                     });
              
              $("body [id]").each(function(){
                                  var ids = $(this).attr("id");
                                  if( $("body [id="+ids+"]").length >= 2 ){
                                  console.log("id为"+ids+" 的重复了。");
                                  }    
                                  });
              });
              //TODO check id 重复 http://blog.csdn.net/china_skag/article/details/6915323
            </script>
    </head>
    <body>
        <a name="top"></a>
        
        <!--done-->
        <div id="home">
            <div id="header">
                <div id="blogTitle">
                    <a id="lnkBlogLogo" href="http://www.cnblogs.com/aji88/"></a>
                    
                    <!--done-->
                    <h1><a id="Header1_HeaderTitle" class="headermaintitle" href="http://www.cnblogs.com/aji88/">aji88</a></h1>
                    <h2 onclick="console.log('do biz method');">不在沉默中爆发，就在沉默中死亡</h2>
                    
                    
                    
                    
                </div><!--end: blogTitle 博客的标题和副标题 -->
            </div><!--end: header 头部 -->
            
            <div id="main">
                <div id="mainContent">
                    <div class="forFlow">
                        <div id="navigator">
                            
                            <!--done-->
                            <ul id="navList">
                                <li><a id="MyLinks1_HomeLink" class="menu" href="http://www.cnblogs.com/">博客园</a></li>
                                <li><a id="MyLinks1_IngLink" class="menu" href="http://home.cnblogs.com/ing/">闪存</a></li>
                                <li><a id="MyLinks1_MyHomeLink" class="menu" href="http://www.cnblogs.com/aji88/">首页</a></li>
                                <li><a id="MyLinks1_NewPostLink" class="menu" rel="nofollow" href="http://i.cnblogs.com/EditPosts.aspx?opt=1">新随笔</a></li>
                                <li><a id="MyLinks1_ContactLink" accesskey="9" class="menu" rel="nofollow" href="http://space.cnblogs.com/msg/send/db%27s+jim">联系</a></li>
                                <li><a id="MyLinks1_Admin" class="menu" rel="nofollow" href="http://i.cnblogs.com/">管理</a></li>
                                <li><a id="MyLinks1_Syndication" class="menu" href="http://www.cnblogs.com/aji88/rss">订阅</a>
                                    <a id="MyLinks1_XMLLink" class="aHeaderXML" href="http://www.cnblogs.com/aji88/rss"><img src="http://www.cnblogs.com/images/xml.gif" alt="订阅" /></a></li>
                            </ul>
                            
                            
                            <div class="blogStats">
                                
                                
                                <!--done-->
                                随笔- 134&nbsp;
                                文章- 2&nbsp;
                                评论- 14&nbsp;
                                
                                
                            </div><!--end: blogStats -->
                        </div><!--end: navigator 博客导航栏 -->
                        
                        
                        <!--done-->
                        <div id="topics">
                            <div class = "post">
                                <h1 class = "postTitle">
                                    <a id="cb_post_title_url" class="postTitle2" href="http://www.cnblogs.com/aji88/archive/2012/07/20/2600492.html">JS的事件监听机制</a>
                                </h1>
                                <div class="clear"></div>
                                <div class="postBody">
                                    <div id="cnblogs_post_body"><p><span>很久以前有个叫Netscape的姑娘，她制订了Javascript的一套事件驱动机制（即事件捕获）</span></p>
                                        <p><span>后来又有一个叫&ldquo;IE&rdquo;的小子，这孩子比较傲气，他认为&ldquo;凭什么我要依照你的规则走&rdquo;，于是他又创造了一套自己的规则（事件冒泡）</span></p>
                                        <p><span>再后来，有个叫W3C的媒婆，想撮合这两个孩子，将他们的特点融合在了一起，这下，事件产生的顺序变成：</span></p>
                                        <p><span><span>事件从根节点开始，逐级派送到子节点，若节点绑定了事件动作，则执行动作，然后继续走，这个阶段称为&ldquo;</span><strong><span>捕获阶段(Capture)</span></strong><span>&rdquo;；</span><br /><span>执行完捕获阶段后，事件由子节点往根节点派送，若节点绑定了事件动作，则执行动作，然后继续走，这个阶段称为&ldquo;</span><strong><span>冒泡阶段(Bubble)</span></strong><span>&rdquo;。</span></span></p>
                                        <p><span>&nbsp;</span></p>
                                        <p><span><span>&nbsp;</span></span></p>
                                        <p>
                                        <input type="password" />
                                        </p>
                                        <p><span><span>善良的Netscape以及其姐妹们都接受了媒婆的建议，采用了新的事件规则，而骄傲固执的IE小子始终按照自己的规则执行。最终使得这成为困扰前端开发人员的兼容性问题之一。那么，怎么绑定事件呢？</span></span></p>
                                        <p><span><span>由于这两派浏览器的差异，其绑定的方法也不一样，其中，遵循标准的浏览器使用W3C定义的addEventListener函数绑定，函数定义如下：</span><br /><span><br /></span></span></p>
                                        <p><span><span>function addEventListener(string eventFlag, function eventFunc, [bool useCapture=false])</span><br /><span>eventFlag : 事件名称，如click、mouseover&hellip;</span><br /><span>eventFunc: 绑定到事件中执行的动作</span><br /><span>useCapture: 指定是否绑定在捕获阶段，true为是，false为否，默认为true</span><br /><span>在事件监听流中可以使用event.stopPropagation()来阻止事件继续往下流</span></span></p>
                                        <p><span><span>&nbsp;</span></span></p>
                                        <p><span><span>IE中使用自有的attachEvent函数绑定时间，函数定义如下：</span><br /><span>function attachEvent(string eventFlag, function eventFunc)</span><br /><span>eventFlag: 事件名称，但要加上on，如onclick、onmouseover&hellip;</span><br /><span>eventFunc: 绑定到事件中执行的动作</span><br /><strong><span>在事件监听流中可以使用window.event.cacenlBubble=false来阻止事件继续往下流</span></strong></span></p>
                                        <p><span>总结：addEventListener(string eventFlag, function eventFunc, [bool useCapture=false])，针对ff，chrome，safari浏览器，false指冒泡阶段，默认为true，指捕获阶段。不过一般我们都用false。</span></p>
                                        <p><span>&nbsp;attachEvent(string eventFlag, function eventFunc)，针对ie系列、还有opera浏览器，少了事件处理机制的参数，只指定事件类型（别忘了on）和触发哪个函数。</span></p>
                                        <p><span>&nbsp;</span></p>
                                        <p><span><span>有了这些认知之后，有了大致的思路，对应的代码：</span></span></p>
                                        <p><span><span>if(document.addEventListener){</span></span></p>
                                        <p><span><span>document.addEventListener('click', hideBox, false);</span></span></p>
                                        <p><span><span>在document绑定信息框（竖的那个）隐藏函数（即随便点html页面的哪里关闭展开的信息框，这也是使用document.addEventListener的原因，要帮在文档上）</span></span></p>
                                        <p><span><span>document.getElementById('status_hide').addEventListener('click', showBox, false);</span></span></p>
                                        <p><span><span>在status_hide节点绑定信息框展开(详细的那个)函数并停止事件流（即点击竖的这个，展开详细的那个）</span></span></p>
                                        <p><span><span>document.getElementById('status_show').addEventListener('click', stopEvent, false);</span></span></p>
                                        <p><span><span><span><strong>因为false确定的是事件冒泡，为了防止点详情的时候，向上冒泡到document，触发document设置的click时hidebox方法，在status_show我们要绑定阻止事件流函数。</strong></span></span></span></p>
                                        <p><span><span>}</span></span></p>
                                        <p><span><span>这个明白了，针对ie再写个attachEvent的就可以了，当然ie的参数只用2个就可以了，它的时间处理机制就是冒泡不用额外设置。</span></span></p>
                                        <p><span><span>&nbsp;</span></span></p>
                                        <p><span><span>最后要说说</span></span><span>这段函数。</span></p>
                                        <p><span>var stopEvent = function(event){ e = event || window.event; if(e.stopPropagation){ e.stopPropagation(); }else { e.cancelBubble = true; } };</span></p>
                                        <p><span><span>可以确定它的作用是防止前面提到的冒泡，引发不该引发的click事件。</span></span></p>
                                        <p><span><span>可是它呢function(event){e = event || window.event}</span></span></p></div><div id="MySignature"></div>
                                    <div class="clear"></div>
                                    <div id="blog_post_info_block">
                                        <div id="BlogPostCategory"></div>
                                        <div id="EntryTag"></div>
                                        <div id="blog_post_info">
                                        </div>
                                        <div class="clear"></div>
                                        <div id="post_next_prev"></div>
                                    </div>
                                    
                                    
                                </div>
                                <div class = "postDesc">posted @ <span id="post-date">2012-07-20 08:47</span> <a href='http://www.cnblogs.com/aji88/'>db's jim</a> 阅读(<span id="post_view_count">...</span>) 评论(<span id="post_comment_count">...</span>)  <a href ="http://i.cnblogs.com/EditPosts.aspx?postid=2600492" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(2600492);return false;">收藏</a></div>
                            </div>
                            
                            
                        </div><!--end: topics 文章、评论容器-->
                        <a name="!comments"></a><div id="blog-comments-placeholder"></div>
                        <div id="comment_form" class="commentform">
                            <a name="commentform"></a>
                            <div id="divCommentShow"></div>
                            <div id="comment_nav"><span id="span_refresh_tips"></span><a href="javascript:void(0);" id="lnk_RefreshComments" onclick="return RefreshCommentList();">刷新评论</a><a href="#" onclick="return RefreshPage();">刷新页面</a><a href="#top">返回顶部</a></div>
                            <div id="comment_form_container"></div>
                            <div class="ad_text_commentbox" id="ad_text_under_commentbox"></div>
                            <div id="site_nav_under"><a href="http://www.cnblogs.com/" target="_blank" title="开发者的网上家园">博客园首页</a><a href="http://q.cnblogs.com/" target="_blank" title="程序员问答社区">博问</a><a href="http://news.cnblogs.com/" target="_blank" title="IT新闻">新闻</a><a href="http://home.cnblogs.com/ing/" target="_blank">闪存</a><a href="http://job.cnblogs.com/" target="_blank">程序员招聘</a><a href="http://kb.cnblogs.com/" target="_blank">知识库</a></div>
                            <div id="opt_under_post"></div>
                            
                            <div id="ad_under_post_holder">
                                
                                <script type='text/javascript'>
                                    try {
                                        if (enableGoogleAd) {
                                            googletag.cmd.push(function () {
                                                               googletag.defineSlot('/1090369/cnblogs_blogpost_C1_sitehome', [300, 250], 'div-gpt-ad-1346480159711-0').addService(googletag.pubads());
                                                               googletag.defineSlot('/1090369/cnblogs_blogpost_C2', [468, 60], 'div-gpt-ad-1410860226396-0').addService(googletag.pubads());
                                                               googletag.pubads().enableSingleRequest();
                                                               googletag.enableServices();
                                                               });
                                        };
                                    } catch (e) { }
                                </script>
                                <div id="google_ad_c1" class="c_ad_block">
                                    <div id='div-gpt-ad-1346480159711-0' style='width:300px; height:250px;'>
                                        <script type='text/javascript'>
                                            try {
                                                if (enableGoogleAd) {
                                                    googletag.cmd.push(function () { googletag.display('div-gpt-ad-1346480159711-0'); });
                                                } else {
                                                    $('#div-gpt-ad-1346480159711-0').hide();
                                                }
                                            } catch (e) { }
                                        </script>
                                    </div>
                                </div>
                            </div>
                            <div id="under_post_news"></div>
                            <div id="google_ad_c2" class="c_ad_block">
                                <div id='div-gpt-ad-1410860226396-0' style='width:468px; height:60px;'>
                                    
                                </div>
                            </div>
                            <div id="under_post_kb"></div>
                            <div id="HistoryToday" class="c_ad_block"></div>
                            
                        </div>
                        
                    </div><!--end: forFlow -->
                </div><!--end: mainContent 主体内容容器-->
                
                <div id="sideBar">
                    <div id="sideBarMain">
                        
                        <!--done-->
                        <div class="newsItem">
                            <h3 class="catListTitle">公告</h3>
                            <div id="blog-news"></div>
                        </div>
                        
                        <div id="calendar"><div id="blog-calendar" style="display:none"></div></div>
                        
                        <DIV id="leftcontentcontainer">
                            <div id="blog-sidecolumn"></div>
                        </DIV>
                        
                    </div><!--end: sideBarMain -->
                </div><!--end: sideBar 侧边栏容器 -->
                <div class="clear"></div>
            </div><!--end: main -->
            <div class="clear"></div>
            <div id="footer">
                
                <!--done-->
                Copyright &copy;2015 db's jim
            </div><!--end: footer -->
        </div><!--end: home 自定义的最大容器 -->
    </body>
</html>



